package modulos.usuario.vista;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.List;
import javax.swing.JOptionPane;
import modulos.usuario.modelo.Cuenta_Usuario;
import modelo.Persona;
import modulos.usuario.modelo.Usuario;

/**
 *
 * @author caesar
 */
public class iFrmMyNewKey extends javax.swing.JDialog {

    List<Object[]> usuarioActivo = null;
    Cuenta_Usuario eCuenta_Usuario = new Cuenta_Usuario();
    Persona findPersona = new Persona();
    Usuario findUsuario = new Usuario();
    Cuenta_Usuario findCuenta_Usuario = new Cuenta_Usuario();
    
    public iFrmMyNewKey(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }
    
    public iFrmMyNewKey(java.awt.Frame parent, boolean modal, List<Object[]> currentUser) {
        super(parent, modal);
        initComponents();
        Dimension scrn = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension windw = this.getSize();
        this.setLocation((scrn.width - windw.width)/2,(scrn.height - windw.height)/2 );
        this.usuarioActivo = currentUser;
        showInfoUsuario();
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnCerrar = new javax.swing.JButton();
        btnAplicar = new javax.swing.JButton();
        pnlId = new javax.swing.JPanel();
        txtNombre = new javax.swing.JTextField();
        pnlClaves = new javax.swing.JPanel();
        lblConfirmar = new javax.swing.JLabel();
        txtReKey = new javax.swing.JPasswordField();
        txtNewKey = new javax.swing.JPasswordField();
        lblClaveNueva = new javax.swing.JLabel();
        pnlUsuario = new javax.swing.JPanel();
        chkCambiar = new javax.swing.JCheckBox();
        txtNewUsuario = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cambiar mi contraseña:");
        setResizable(false);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        btnCerrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpgs/agt_home.png"))); // NOI18N
        btnCerrar.setText("Cerrar");
        btnCerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCerrarActionPerformed(evt);
            }
        });
        getContentPane().add(btnCerrar, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 270, 100, -1));

        btnAplicar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpgs/accept.png"))); // NOI18N
        btnAplicar.setText("Aplicar");
        btnAplicar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAplicarActionPerformed(evt);
            }
        });
        getContentPane().add(btnAplicar, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 270, 107, -1));

        pnlId.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Identificación:", javax.swing.border.TitledBorder.LEFT, javax.swing.border.TitledBorder.TOP));
        pnlId.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        txtNombre.setBackground(new java.awt.Color(235, 234, 254));
        txtNombre.setEditable(false);
        txtNombre.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        pnlId.add(txtNombre, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 30, 290, -1));

        getContentPane().add(pnlId, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 12, 330, 70));

        pnlClaves.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Nueva contraseña:", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.TOP));
        pnlClaves.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        lblConfirmar.setFont(new java.awt.Font("Ubuntu", 0, 13)); // NOI18N
        lblConfirmar.setText("Confirmación:");
        pnlClaves.add(lblConfirmar, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 60, -1, -1));

        txtReKey.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtReKeyKeyReleased(evt);
            }
        });
        pnlClaves.add(txtReKey, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 50, 200, -1));

        txtNewKey.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtNewKeyKeyReleased(evt);
            }
        });
        pnlClaves.add(txtNewKey, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 20, 200, -1));

        lblClaveNueva.setFont(new java.awt.Font("Ubuntu", 0, 13)); // NOI18N
        lblClaveNueva.setText("Contraseña:");
        pnlClaves.add(lblClaveNueva, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 30, -1, -1));

        getContentPane().add(pnlClaves, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 170, 330, 90));

        pnlUsuario.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Nombre de usuario:", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.TOP));
        pnlUsuario.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        chkCambiar.setFont(new java.awt.Font("Ubuntu", 0, 13)); // NOI18N
        chkCambiar.setText("Cambiar:");
        chkCambiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkCambiarActionPerformed(evt);
            }
        });
        pnlUsuario.add(chkCambiar, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, -1, -1));

        txtNewUsuario.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtNewUsuario.setEnabled(false);
        txtNewUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtNewUsuarioKeyReleased(evt);
            }
        });
        pnlUsuario.add(txtNewUsuario, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 20, 210, -1));

        getContentPane().add(pnlUsuario, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 90, 330, 70));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void showInfoUsuario()
    {
        try
        {
            if(usuarioActivo.size()==1)
            {   
                for(Object[] o: usuarioActivo)
                {
                    findCuenta_Usuario = (Cuenta_Usuario)o[0];
                    findUsuario = (Usuario)o[1];
                    findPersona = (Persona)o[2];
                }
                txtNombre.setText(findPersona.getNombre() + "  " + findPersona.getApellido());
                txtNewUsuario.setText(findCuenta_Usuario.getNomUsuario().trim());
            }            
        }catch(Exception ex)
        {
            JOptionPane.showMessageDialog(null, "Se ha producido una excepcion:\n" + ex.getMessage(), "Datos de usuario", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    private void btnCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCerrarActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCerrarActionPerformed

    private Cuenta_Usuario SetGetNewDataAccess()
    {
        findCuenta_Usuario.setNomUsuario(txtNewUsuario.getText().trim());
        findCuenta_Usuario.setClave(txtNewKey.getText().trim());
        return findCuenta_Usuario;
    }
    private void btnAplicarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAplicarActionPerformed
        try 
        {
            if(txtNewKey.getText().trim().compareTo(txtReKey.getText().trim())!=0)
            {
                JOptionPane.showMessageDialog(null, "La nueva contraseña y su confirmación no coinciden", "Validación", JOptionPane.WARNING_MESSAGE);
                txtReKey.setSelectionStart(0);
                txtReKey.setSelectionEnd(txtReKey.getText().trim().length());
                txtReKey.requestFocus();
                return;
            }
            
            iFrmKey frmk = new iFrmKey(null, true);
            frmk.setVisible(true);
            if(frmk.clave != null)
            {
                if(frmk.clave.compareTo(findCuenta_Usuario.getClave().trim())==0)
                {
                    eCuenta_Usuario.updatetUsuario(SetGetNewDataAccess());
                    chkCambiar.setSelected(false);
                    txtNewUsuario.setEnabled(false);
                    txtNewKey.setText("".trim());
                    txtReKey.setText("".trim());
                    JOptionPane.showMessageDialog(null, "El cambio de contraseña se realizó correctamente", "Aplicar", JOptionPane.INFORMATION_MESSAGE);
                    btnCerrar.requestFocus();
                }
                else
                {
                    JOptionPane.showMessageDialog(null, "La contraseña actual no es correcta", "Validación", JOptionPane.WARNING_MESSAGE);
                    btnAplicar.requestFocus();
                }
            } 
        } catch (Exception ex) 
        {
            JOptionPane.showMessageDialog(null, "Se ha producido una excepcion:\n" + ex.getMessage(), "Cambio de contraseña", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnAplicarActionPerformed

    private void chkCambiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkCambiarActionPerformed
        if (chkCambiar.isSelected()) {
            txtNewUsuario.setEnabled(true);
            txtNewUsuario.setSelectionStart(0);
            txtNewUsuario.setSelectionEnd(txtNewUsuario.getText().trim().length());
            txtNewUsuario.requestFocus();
        } else 
        {
            txtNewUsuario.setEnabled(false);
            txtNewKey.requestFocus();
        }
    }//GEN-LAST:event_chkCambiarActionPerformed

    private void txtNewUsuarioKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNewUsuarioKeyReleased
        if(evt.getKeyCode() == 10)
            txtNewKey.requestFocus();
    }//GEN-LAST:event_txtNewUsuarioKeyReleased

    private void txtNewKeyKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNewKeyKeyReleased
        if(evt.getKeyCode() == 10)
            txtReKey.requestFocus();
    }//GEN-LAST:event_txtNewKeyKeyReleased

    private void txtReKeyKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtReKeyKeyReleased
        if(evt.getKeyCode() == 10)
            btnAplicar.requestFocus();
    }//GEN-LAST:event_txtReKeyKeyReleased

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(iFrmMyNewKey.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(iFrmMyNewKey.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(iFrmMyNewKey.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(iFrmMyNewKey.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                iFrmMyNewKey dialog = new iFrmMyNewKey(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAplicar;
    private javax.swing.JButton btnCerrar;
    private javax.swing.JCheckBox chkCambiar;
    private javax.swing.JLabel lblClaveNueva;
    private javax.swing.JLabel lblConfirmar;
    private javax.swing.JPanel pnlClaves;
    private javax.swing.JPanel pnlId;
    private javax.swing.JPanel pnlUsuario;
    private javax.swing.JPasswordField txtNewKey;
    private javax.swing.JTextField txtNewUsuario;
    private javax.swing.JTextField txtNombre;
    private javax.swing.JPasswordField txtReKey;
    // End of variables declaration//GEN-END:variables
}
